import io
import os
from PIL import Image


# 把文件夹里所有 webg 格式的转换为  JPEG
def os_photo_convert(folder_path, start_format, finally_format, delete_old_photo):
    """
    :param folder_path: 图片所在目录
    :param start_format: 需要转换的图片格式
    :param finally_format: 转换后的图片格式
    :param delete_old_photo: 是否删除旧照片，默认不删除
    :return:
    """
    # 这里都是给函数一个默认值
    if start_format is None:
        start_format = ".webp"
    if finally_format is None:
        finally_format = ".jpeg"
    if delete_old_photo is None:
        delete_old_photo = False

    # os.listdir(folder_path) 获取本文将内所有文件，遍历给 filename
    for filename_old in os.listdir(folder_path):
        # 判断 file 是否以 start_format 结尾
        if filename_old.endswith(start_format):
            # 拿到除后缀之后的图片名称
            a = len(start_format)
            # 新图片名称
            filename_new = filename_old[:-a] + finally_format
            # 打开原始图片
            img = Image.open(folder_path+filename_old)
            # 将图片转换为二进制数据
            img_byte_array = io.BytesIO()
            # 如果写入的 JPG 则改为 JPEG 格式
            if start_format[1:].upper() == 'JPG':
                b = 'JPEG'
            else:
                b = start_format[1:]
            img.save(img_byte_array, format=b)
            img_byte_array = img_byte_array.getvalue()

            # 将二进制数据转换为webp格式并保存
            new_img = Image.open(io.BytesIO(img_byte_array))
            new_img.save(f'{folder_path}{filename_new}', finally_format[1:])

            # 删除旧图片
            if delete_old_photo is True:
                os.remove(folder_path+filename_old)
        # 非目标格式不进行替换
        else:
            continue


if __name__ == '__main__':
    date_path = r"/Users/admin/Desktop/照片/赵奕欢/"
    date_path1 = r"/Users/admin/Downloads/"
    os_photo_convert(folder_path=date_path1, start_format=".jpg", finally_format=".webp", delete_old_photo=True)
    #  result_path = r"/Users/admin/Downloads/4.png"
    # photo_convert(date_path, result_path)
    print("done")
